﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
public class ChatData
{
    public long myUserId;
    public long opponentUserId;
    public Chat myChat;
    public Chat opponentChat;

    public ChatData() { }
    public ChatData(long myUserId, long opponentUserId, Chat myChat, Chat opponentChat)
    {
        this.myUserId = myUserId;
        this.opponentUserId = opponentUserId;
        this.myChat = myChat;
        this.opponentChat = opponentChat;
    }
}
public class ChatPanel :  AppUI
{
    public Action<long> m_OnSelect;

    public Text candidateText;

    public InputField inputField;

    public Action<string> m_OnSend;

    List<ChatItem> m_CandidateChatItems = new List<ChatItem>();
    private List<ChatItem> m_PlayerChatItems = new List<ChatItem>();


    public Transform chatItemsParent;
    public ChatItem candidateChatItemPref;
    public ChatItem playerChatItemPref;

    public ScrollRect chatListScroll;
    private Vector3 m_NormalPos;

    ZUIAnimTools zTransformAnim;
    public ZUIAnimTools TransformAnim
    {
        get
        {
            if (zTransformAnim == null)
                zTransformAnim = this.gameObject.AddComponent<ZUIAnimTools>();
            return zTransformAnim;
        }
    }
    UserInfo m_TargetUserInfo;
    ChatData m_Data;
    long m_targetUserId;
    public override void Awake()
    {
        base.Awake();

        candidateChatItemPref.gameObject.SetActive(false);
        playerChatItemPref.gameObject.SetActive(false);

    }

    public override void Start()
    {
        base.Start();
        //inputField.onSelect.AddListener(OnInputValueChanged);
        //inputField.onValueChange.AddListener(OnInputValueChanged);
        inputField.onEndEdit.AddListener(OnInputEndEvent);
        m_NormalPos = inputTrans.anchoredPosition;
    }

    public class DialogueData
    {
        public bool  meRequest;
        public Dialogue dialogue;
        public DialogueData(bool meRequest, Dialogue dialogue)
        {
            this.meRequest = meRequest;
            this.dialogue = dialogue;
        }
    }
    Texture2D m_MeIcon;
    Texture2D m_OpponentIcon;
    public void Init(UserInfo targetUserInfo, ChatData data)
    {
        m_Data = data;
        m_TargetUserInfo = targetUserInfo; 
        m_targetUserId = targetUserInfo.userId;
        inputField.text = "";

        Dialogue[] requestDialogues = null;
        if(m_Data.myChat != null)
            requestDialogues = m_Data.myChat.dialogues;

        Dialogue[] receiveDialogues = null;
        if(m_Data.opponentChat != null)
            receiveDialogues = m_Data.opponentChat.dialogues;

        if (receiveDialogues != null || requestDialogues != null)
        {
            List<DialogueData> dialogues = new List<DialogueData>();
            if (requestDialogues != null)
                dialogues.AddRange(requestDialogues.Map(e => new DialogueData(data.myUserId == MGame.instance.MUser.id, e)));
            if (receiveDialogues != null)
                dialogues.AddRange(receiveDialogues.Map(e => new DialogueData(data.opponentUserId == MGame.instance.MUser.id, e)));

            UnityFunctions.ClearList(m_CandidateChatItems);
            UnityFunctions.ClearList(m_PlayerChatItems);

            dialogues.Sort((a, b) => a.dialogue.time.CompareTo(b.dialogue.time));

            if (m_MeIcon)
                DestroyImmediate(m_MeIcon);
            if (m_OpponentIcon)
                DestroyImmediate(m_OpponentIcon);

            UnityFunctions.GetTextureWithUrl(MGame.instance.MUser.userInfo.icon,
            (iconTex) =>
            {
                m_MeIcon = iconTex;
                var oppo = dialogues.Find(e => !e.meRequest);
                if (oppo != null)
                {
                    UnityFunctions.GetTextureWithUrl(targetUserInfo.icon, (oppoIcon) =>
                    {
                        m_OpponentIcon = oppoIcon;

                        InitDialogItems(dialogues);
                    });
                }
                else
                {
                    InitDialogItems(dialogues);
                }

               
            });

            //m_MeIcon = UnityFunctions.GetTextureWithByte(MGame.instance.MUser.userInfo.icon);


        }
       
        this.candidateText.text = targetUserInfo.name;

        StartCoroutine(UnityFunctions.AdjustItemsLayout(transform));

        this.chatListScroll.verticalNormalizedPosition = 0;
        Canvas.ForceUpdateCanvases();

        DoActionDelay.DelayAction(.2f, () =>
        {
            this.chatListScroll.verticalNormalizedPosition = 0;
            Canvas.ForceUpdateCanvases();
        });
        //m_ToHide = false;
    }

    void InitDialogItems(List<DialogueData> dialogues)
    {
        for (int i = 0; i < dialogues.Count; i++)
        {
            ChatItem newItem;
            Texture2D icon = null;
            if (!dialogues[i].meRequest)
            {
                newItem = Instantiate(candidateChatItemPref, chatItemsParent);
                m_CandidateChatItems.Add(newItem);
                icon = m_OpponentIcon;
            }
            else
            {
                newItem = Instantiate(playerChatItemPref, chatItemsParent);
                m_PlayerChatItems.Add(newItem);
                icon = m_MeIcon;
            }

            //Debug.Log($"chat item:{selectData.candidateId} content:{selectData.dialogues[i].content}");
            newItem.gameObject.SetActive(true);

            //var iconRect = newItem.icon.GetComponent<RectTransform>();
            newItem.Init(icon, dialogues[i].dialogue.message);
        }
    }

    private bool m_InTexting;
    public RectTransform inputTrans;
    private void OnInputValueChanged(string value)
    {
        if (!m_InTexting)
        {
            m_InTexting = true;
#if UNITY_EDITOR
            //return;
#endif

            var pos = m_NormalPos;
            pos.y = 960;
            //transform.localPosition = pos;
            TransformAnim.RectMove(inputTrans, pos, .2f, null, ZUIAnimTools.EaseType.OutSine);
        }
    }

    private void OnInputEndEvent(string arg0)
    {
        m_InTexting = false;
#if UNITY_EDITOR
        //return;
#endif
        TransformAnim.StopAllAnim();
        TransformAnim.RectMove(inputTrans, m_NormalPos, .2f, null, ZUIAnimTools.EaseType.OutSine);
    }
    void OnSelectItem(ChatCandidateItem skinsItem)
    {
        if (!skinsItem)
            return;

        this.m_OnSelect?.Invoke(skinsItem.Id);
    }

    public void OnClickSend()
    {
        string sendStr = this.inputField.text;

        RequestServerController.instance.ReqSendDialogue(MGame.instance.MUser.id, m_targetUserId, sendStr
            , (chat) =>
            {
                if (chat != null)
                {
                    //var chat = MGame.instance.MUser.AddDialogue(MGame.instance.MUser.id, m_targetUserId, sendStr, dia.time);
                    GameDebug.Log($"req dialogues count:{chat.dialogues.Length}");
                    m_Data.myChat = chat;
                    Refresh(m_Data);
                }
                else
                {
                    GameDebug.LogError($"chat is null");
                }
            });
    }


    //bool m_ToHide;
    //public override  void GoBack()
    //{
    //    //if (m_ToHide)
    //    //    return;

    //    //m_ToHide = true;

    //    UIController.ShowUI<MainPanel>();
    //}

    public void Refresh(ChatData chat)
    {
        Init(m_TargetUserInfo, chat);
    }
}